package util;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.RoundingMode;
import java.text.NumberFormat;

import engine.ChessEngine;

import beans.Color;
import beans.Move;
import board.Game;

/**
 * Class with 2 static methods used to write a PGN file from a game
 * 
 * @author Josep M Sobrepere
 *
 */
public class PGNWriter {
	
		
	/**
	 * @param game the game
	 * @param file the destination of the file
	 * @throws IOException
	 */
	public static void writeFile(Game game, String file) throws IOException{
		String pgn =  getPGN(game);
		
		FileWriter outFile = new FileWriter(file);
		PrintWriter out = new PrintWriter(outFile);
		for(String key: game.getInfo().keySet())
			out.println("["+key+ " \"" + game.getInfo().get(key) + "\"]");
		
		out.println("");
		out.print(pgn);
		 out.close();
		 outFile.close();
	}
	
	
	/**
	 * Generates a String containing the PGN of the game
	 * @param game the game
	 * @return a String containing the PGN of the game
	 */
	public static String getPGN(Game game){
		StringBuilder sb = new StringBuilder();
		float score=0;
		
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(2);
		nf.setMinimumFractionDigits(2);
		nf.setMinimumIntegerDigits(1);
		nf.setMaximumIntegerDigits(3);
		nf.setRoundingMode(RoundingMode.HALF_EVEN);
		
		for(Move move: game.getMoves()){
			if(move.getPiece().getColor()== Color.WHITE){
				sb.append(" ").append(move.getNumber()).append(".");
			}
			else if(move.getPreviousMove().getAnalysis()!=null){
				sb.append(" ").append(move.getNumber()).append("...");				
			}
			sb.append(" ").append(move.getShortAlgebraicNotation());
			
			if(move.getAnalysis()!=null){
				score = move.getAnalysis().getScore();
				score=score/100;
				if(move.getAnalysis().isBookMove()){
					sb.append("{").append("Book").append("}");
				}else{
					sb.append("{").append(nf.format(score)).append("}");
				}
				
				
				if(move.getPreviousMove() !=null && move.getPreviousMove().getAnalysis().isDeeplyAnalized()){
					sb.append("(");
					for(Move variation: move.getPreviousMove().getAnalysis().getBestContinuation()){
						if(variation.getPiece().getColor()== Color.WHITE){
							sb.append(" ").append(variation.getNumber()).append(".");
						}
						else if(variation.equals(move.getPreviousMove().getAnalysis().getBestContinuation().get(0))){
							sb.append(" ").append(variation.getNumber()).append("...");				
						}
						sb.append(" ").append(variation.getShortAlgebraicNotation());
					}
					score = move.getPreviousMove().getAnalysis().getScore();	
					score=score/100;
					sb.append("{").append(nf.format(score)).append("}").append(")");
				}
			}
		}
		return sb.toString();		
	}
}
